//
//  BGHomeViewController.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/19.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

private let identifiter = "HomeCell"

class BGHomeViewController: BGBaseViewController {
    
    lazy var statusList: BGHomeViewModel = BGHomeViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitView?.setupVisitorViewInfo(nil, title: nil)
        }else {
            setupTableInfo()
            getHomeData()
        }
    }
    
    private func setupTableInfo() {
        let tab: UITableView = tableView
        tab.registerClass(BGHomeCell.self, forCellReuseIdentifier: identifiter)
        tab.estimatedRowHeight = 200
        tab.separatorStyle = .None
        
        //添加刷新控件
        tab.tableFooterView = indicator
    }
    
    
    //MARK: - 懒加载 
    //菊花
    private lazy var indicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        //给菊花设置颜色
        view.color = ThemeColor
        return view
    }()
    
    private lazy var  refresh: UIRefreshControl = UIRefreshControl()

}


//MARK: - 数据源代理方法
extension BGHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusList.statusList.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifiter) as? BGHomeCell
        
        cell!.cellModel = self.statusList.statusList[indexPath.row]
        
        return cell!
    }
}

//MARK: - 代理方法
extension BGHomeViewController {
    //
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //如果是最后一行而且菊花没转,就让菊花转动
        if indexPath.row == self.statusList.statusList.count-1 && !self.indicator.isAnimating() {
            self.indicator.startAnimating()
            getHomeData()
        }
        
    }
    
}

//MARK: - 请求数据
extension BGHomeViewController {
    
    private func getHomeData() {
        
        self.statusList.loadHomeData(self.indicator.isAnimating()) { (isSuc) in
            //停止动画
            self.stopRefreshing()
            //如果失败
            if !isSuc {
                print("读取首页信息失败")
                return
            }
            self.tableView.reloadData()
        }
    }
    
    //停止动画
    private func stopRefreshing() {
        self.indicator.stopAnimating()
    }
    
}
